package com.qf.oa_system.controller;

import com.qf.oa_system.entity.*;
import com.qf.oa_system.service.ClassmasterService;
import com.qf.oa_system.service.HeadStudentService;
import com.qf.oa_system.service.LeavesService;
import com.qf.oa_system.service.StudentSorceServic;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * ?????α(Classmaster)表控制层
 *
 * @author makejava
 * @since 2020-06-03 20:26:21
 */
@Controller
@RequestMapping("/classmaster")
public class ClassmasterController {
    /**
     * 服务对象
     */
    @Resource
    private ClassmasterService classmasterService;

    @Resource
    private LeavesService leavesService;

    @Resource
    private HeadStudentService headStudentService;


    @Autowired
    private StudentSorceServic studentSorceServic;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Classmaster selectOne(Integer id) {
        return this.classmasterService.queryById(id);
    }

    /**
     * 跳转到个人请假页面
     *
     * @return
     */
    @RequestMapping("/toClassMeasterHoliday")
    public String toClassMeaster(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Classmaster classmaster1 = classmasterService.queryClassmasterByUserId(user.getUserId());
        Classmaster classmaster = classmasterService.queryById(classmaster1.getMasId());
        model.addAttribute("clazz", classmaster);
        return "headmeastreholiday";
    }

    /**
     * 请假条的添加
     *
     * @param leaves
     * @return
     */
    @RequestMapping("/insertHoliday")
    public String insertHoliday(Leaves leaves) {
        leavesService.insert(leaves);
        return "index";
    }

    /**
     * 跳转到学生信息查询页面
     *
     * @return
     */
    @RequestMapping("/toStudentsInformtion")
    public String toStudentInformtion(Model model) {
        List<StudentsAndClasses> studentsAndClasses = headStudentService.queryStudentByTyp();
        model.addAttribute("student", studentsAndClasses);
        return "headmeasterstudent";
    }

    /**
     * 学生管理表的导出
     * 选中提交的名单进行
     *
     * @param one
     * @return
     */
    @RequestMapping("/getStudentInformtion")
    @ResponseBody
    public String getStudentInformation(@RequestParam(value = "one") List<Integer> one, HttpServletResponse response) {

        //创建xls文件
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        //通过hss创建sheet
        HSSFSheet sheet = hssfWorkbook.createSheet("学生信息表");
        //创建第一行的内容
        HSSFRow row = sheet.createRow(0);
        //创建第一个单元格
        HSSFCell cell = row.createCell(0);
        //给单元个赋值
        cell.setCellValue("学生信息表");
        //合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

        //第二行的内容
        String[] str = {"序号", "姓名", "性别", "年龄", "地址", "电话", "班级"};
        //创建第二行的表单内容
        HSSFRow row1 = sheet.createRow(1);
        //创建第二行单元格内容
        for (int i = 0; i < str.length; i++) {
            //第二行的内容
            row1.createCell(i).setCellValue(str[i]);
        }

        //遍历循环数据进行添加
        for (int i = 0; i < one.size(); i++) {
            StudentsAndClasses students = headStudentService.queryStudentByStuId(one.get(i));
            //创建第几行
            HSSFRow row2 = sheet.createRow(i + 2);
            row2.createCell(0).setCellValue(i + 1);
            row2.createCell(1).setCellValue(students.getStuName());
            row2.createCell(2).setCellValue(students.getStuSex());
            row2.createCell(3).setCellValue(students.getStuBirthday());
            row2.createCell(4).setCellValue(students.getStuAddress());
            row2.createCell(5).setCellValue(students.getStuPhone());
            row2.createCell(6).setCellValue(students.getClassName());
        }

//        String string = UUID.randomUUID().toString();
//        String str1 = string.substring(0, 7) + ".xls";
        //        //输出
        try {
            //获取桌面
            FileSystemView fsv = FileSystemView.getFileSystemView();
            File file1 = fsv.getHomeDirectory();

            String string = UUID.randomUUID().toString();
            String str1 = string.substring(0, 7);
            //生成文件
            File file2 = new File(file1.getPath() + File.separator + "学生信息表" + str1 + ".xls");
//            if (!file2.exists()){
//                file2.mkdir();
//            }
            FileOutputStream file = new FileOutputStream(file2);
            hssfWorkbook.write(file);
            file.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        try {
//            str1 = new String(str1.getBytes(),"UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        try {
//            //识别excel
//            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(str1, "UTF-8"));
//            response.setContentType("application/vnd.ms-excel");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            ServletOutputStream out = response.getOutputStream();
//            hssfWorkbook.write(out);
//            out.flush();
//            out.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


        return "nihao";
    }


    /**
     * excel文件的上传
     *
     * @return
     */
    @RequestMapping("/HSWorkBook")
    public String insertStudentInformation(@RequestParam("file") MultipartFile file) {

        //创建file
//        try {
//            String filename = file.getOriginalFilename();
//            System.out.println("路径"+ResourceUtils.getFile(filename));
//
//            FileInputStream fileInputStream = new FileInputStream(filename);
//            //判断是什么版本的
//
//            Workbook workbook = this.getworkBook(filename,fileInputStream);
//            System.out.println(workbook);
//            //获取首页表
//            Sheet sheetAt = workbook.getSheetAt(0);
//            //循环返回字段
//            int firstRowNum = sheetAt.getFirstRowNum();
//            int lastRowNum = sheetAt.getLastRowNum();
//            System.out.println(firstRowNum);
//            System.out.println(lastRowNum);
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


        /**
         * 问题，只显示一个数据的结果，同时循环不对
         */
        try {
            //创建输入流
            InputStream inputStream = file.getInputStream();
            //获取名称
            String fileName = file.getOriginalFilename();
            //判断什么版本
            Workbook workbook = this.getworkBook(fileName, inputStream);

            //获取文件中的表格
            Sheet sheetAt = workbook.getSheetAt(0);
            //获取文件中的长度从0开始
            int lastRowNum = sheetAt.getLastRowNum();
            List<StudentsAndClasses> list = new ArrayList<>();
            StudentsAndClasses student = null;
            for (int i = 0; i <= sheetAt.getLastRowNum(); i++) {
                Row row = sheetAt.getRow(i + 2);

                student = new StudentsAndClasses();
                //当超出sheet的长度后，跳出循环
                if (i + 2 > lastRowNum) {
                    break;
                }
                //输出循环
                System.out.println(sheetAt.getLastRowNum());
//                System.out.println(student.setStuId((int) row.getCell(0).getNumericCellValue()););
                student.setStuName(row.getCell(1).getStringCellValue());
                student.setStuSex(row.getCell(2).getStringCellValue());
                student.setStuBirthday(row.getCell(3).getStringCellValue());
                student.setStuAddress(row.getCell(4).getStringCellValue());
                student.setStuPhone(row.getCell(5).getStringCellValue());
                student.setClassName(row.getCell(6).getStringCellValue());
//                System.out.println("最后一个数" + row.getLastCellNum());

                list.add(student);
            }

            //写入数据库
            for (StudentsAndClasses studentsAndClasses : list) {
                int i = headStudentService.insertStudentsByExcel(studentsAndClasses);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/classmaster/toStudentsInformtion";
    }

    public Workbook getworkBook(String fileName, InputStream inputStream) throws IOException {
        Workbook workbook = null;
        if (fileName.endsWith(".xls")) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return workbook;
    }


    /**
     * 去
     * 学生请假表
     *
     * @param leaveTab
     * @param model
     * @return
     */
    @RequestMapping("/toStudentsHoliday")
    public String queryLeavesByTab(Integer leaveTab, Model model) {
        List<StudentsAndLeaves> leaves = headStudentService.queryLeavesByTab(leaveTab);
        model.addAttribute("leaves", leaves);
        return "headmsstudentholiday";
    }

    /**
     * 同意申请
     *
     * @param leaveId
     * @return
     */
    @RequestMapping("/success")
    public String success(Integer leaveId) {
        headStudentService.success(leaveId);
        return "redirect:/classmaster/toStudentsHoliday";
    }


    /**
     * 老师查款学生周报
     *
     * @return
     */
    @RequestMapping("/toWeeklyStudents")
    public String toWeeklyStudents(Model model) {
        List<WeeklyStudents> weekly = headStudentService.queryWeeklyStudents();
        model.addAttribute("weekly", weekly);
        return "weeklystudents";
    }

    @RequestMapping("/queryStudentSocre")
    public String getStudent(Model model){
        List<StudentSorce> studentSocres = studentSorceServic.queryStudent();
        model.addAttribute("score",studentSocres);
        return "studentSorce";
    }

    /**
     * 矢量图
     * @param sId
     * @return
     */
    @RequestMapping("/queryStudent")
    @ResponseBody
    public Double[] getStudentsSocre(int sId){
        StudentsSS studentsSSES = headStudentService.queryStudentsSS(sId);
        System.out.println(studentsSSES);
        Double[] str = new Double[4];
        str[0] = studentsSSES.getOne();
        str[1] = studentsSSES.getTow();
        str[2] = studentsSSES.getThree();
        str[3] = studentsSSES.getFour();

        return str;
    }
}